usePhoneInput
usePhoneInput is a hook for providing phone formatting to existing input components.
Use phone
(as value), handlePhoneValueChange
(as onChange callback) and inputRef
(as passed ref) to handle input.
Usage Example
// import { usePhoneInput } from 'react-international-phone';
const {
inputValue,
phone,
country,
setCountry,
handlePhoneValueChange,
inputRef,
} = usePhoneInput({
defaultCountry: 'us',
value: '+1 (234)',
onChange: ({ phone, inputValue, country }) => {
// make something on change
},
});
Hook arguments
value
Phone value.
- Type:
string
- Default:
""
onChange
Callback that calls on phone change
- Type:
(data: { phone: string; inputValue: string; country: ParsedCountry }) => void
- Default:
undefined
defaultCountry
Default country value (iso2).
- Type:
CountryIso2
- Default:
"us"
countries
An array of available countries to select (and guess)
- Type:
CountryData[]
- Default:
defaultCountries
prefix
Prefix for phone value.
- Type:
string
- Default:
"+"
defaultMask
This mask will apply on countries that does not have specified mask.
- Type:
string
- Default:
"............"
charAfterDialCode
Char that renders after country dial code.
- Type:
string
- Default:
" "
historySaveDebounceMS
Save value to history if there were not any changes in provided milliseconds timeslot. Undo/redo (ctrl+z/ctrl+shift+z) works only with values that are saved in history
- Type:
number
- Default:
200
disableCountryGuess
Disable country guess on value change. onCountryGuess
callback would not be called.
- Type:
boolean
- Default:
false
disableDialCodePrefill
Disable dial code prefill on initialization. Dial code prefill works only when empty phone value have been provided.
- Type:
boolean
- Default:
false
forceDialCode
Always display the dial code. Dial code can't be removed/changed by keyboard events, but it can be changed by pasting another country phone value.
- Type:
boolean
- Default:
false
disableDialCodeAndPrefix
Display phone value will not include passed dialCode
and prefix
if set to true
. forceDialCode
value will be ignored.
- Type:
boolean
- Default:
false
disableFormatting
Disable phone value mask formatting. All formatting characters will not be displayed, but the mask length will be preserved.
- Type:
boolean
- Default:
false
inputRef
Ref for the input element.
- Type:
React.MutableRefObject<HTMLInputElement | null>
- Default:
undefined
Returned values
inputValue
Formatted phone string. Value that should be rendered inside input element.
- Type:
string
phone
Phone in E164 format.
- Type:
string
handlePhoneValueChange
Change handler for input component.
- Type:
(e: React.ChangeEvent<HTMLInputElement>) => string
inputRef
Ref object for input component (handles caret position, focus and undo/redo).
- Type:
React.RefObject<HTMLInputElement>
country
Current country object.
- Type:
ParsedCountry
setCountry
Country setter.
- Type:
(country: CountryIso2, options?: { focusOnInput: boolean })) => void